package com.feiyu.aop;

import com.alibaba.fastjson.JSONObject;
import com.feiyu.mapper.OperateLogMapper;
import com.feiyu.pojo.OperateLog;
import com.feiyu.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Properties;


@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private OperateLogMapper operateLogMapper;
    //切面表达式
    @Around("@annotation(com.feiyu.aop.FeiYuLog)")


    public Object LogRecord(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取id
        String jwt = httpServletRequest.getHeader("token");
        //简析token
        Claims claims = JwtUtils.parseJWT(jwt);


        Integer operateUser = (Integer) claims.get("id");

        log.info("操作人id{ }" + operateUser);

        //运行时间
        LocalDateTime operateTime = LocalDateTime.now();

        //对象名
        String name = joinPoint.getTarget().getClass().getName();
        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法名
        String methodName = joinPoint.getSignature().getName();
        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);


        //操作时间
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        //方法返回值
        String returnValue = JSONObject.toJSONString(result);

        //操作耗时
        Long costTime = end - begin;

        OperateLog operateLog = new OperateLog(null,
                operateUser, operateTime, className,
                methodName, methodParams, returnValue, costTime);
        operateLogMapper.InsertLog(operateLog);

        return result;

    }


}
